import logging
import os

from django.http import HttpResponse
from django.shortcuts import render
from django.utils.translation import ugettext as _

from freenasUI.freeadmin.views import JsonResp
from freenasUI.middleware.notifier import notifier
from . import forms, models

log = logging.getLogger('failover.views')


def failovers_sync_peer(request, oid, fromto):

    #FIXME: import from tools.alert
    SYNC_FILE = '/var/tmp/sync_failed'

    if request.method == "POST":
        if fromto == "to" and os.path.exists(SYNC_FILE):
            os.unlink(SYNC_FILE)
        try:
            failover = notifier().failover_sync_peer(fid=oid, fromto=fromto)
            assert failover is not False
            return JsonResp(
                request,
                message=_("You have successfully synced %s peer %s") % (
                    fromto,
                    failover.ipaddress,
                    )
                )
        except ValueError as e:
            if fromto == "to":
                open(SYNC_FILE, 'w').close()
            return JsonResp(
                request,
                error=True,
                message='An error occured: %s' % str(e)
            )
        except:
            if fromto == "to":
                open(SYNC_FILE, 'w').close()
            return JsonResp(
                request, error=True, message='An error occurred...'
            )
    else:
        failover = models.Failover.objects.get(id=oid)
        return render(
            request,
            "system/failover_sync_%s_peer.html" % (fromto),
            {
                'failover': failover,
            }
        )


def failovers_status(request):
    if not hasattr(notifier, 'failover_status'):
        status = ''
    else:
        status = notifier().failover_status()
    return HttpResponse(status)


def failovers_force_master(request):
    notifier().failover_force_master()
    return JsonResp(request, message='Failover force master initiated')


def hareplication(request):
    if request.method == 'POST':
        form = forms.HAReplicationForm(request.POST)
        if form.is_valid():
            form.commit()
            return JsonResp(
                request,
                message=_("HA Replication successfully updated.")
            )
    else:
        form = forms.HAReplicationForm()
    return render(request, 'storage/hareplication.html', {
        'form': form,
    })
