# -*- coding: utf-8 -*-
import os
os.environ["HTTPGUARD_SETTINGS"] = "/opt/httpguard/master/conf/config.py"
from app import db, Dns_provider, Line_group, Config, line, Task
from public_func import make_msg,mark_task_start, mark_task_success, mark_task_failed, mark_task_del
from sqlalchemy import desc
import app
from time import sleep
import time
import requests
import json
import ntpath
import sys
import datetime
from cloudxns.api import *
import httplib
import socket
from collections import OrderedDict

def heartbeat(name):
    heartbeat_file = os.path.join("/tmp",name + ".heartbeat")
    with open(heartbeat_file,"w") as fp:
        fp.write("")

def add_dnspod_record(auth, domain_id, hostname, line_id, ip, ttl, task_id, line_auto_id):
    auth = json.loads(auth)
    id = auth["id"]
    token = auth["token"]
    login_token = "{id},{token}".format(id=id, token=token)
    try:
        data = {"login_token":login_token,"format":"json","domain_id":domain_id,"sub_domain":hostname, "record_type":"A","record_line_id":line_id,"value":ip,"ttl":ttl}
        headers = {"User-Agent":"python requests client/1.0.0(admin@centos.bz)"}
        r = requests.post("https://dnsapi.cn/Record.Create",data=data,timeout=20,headers=headers)
        status_code = r.status_code
        if status_code != 200:
            return False, "failed: https://dnsapi.cn/Record.Create return status code: {status_code}".format(status_code=status_code)

        content = r.content

        try:
            content = json.loads(content,object_pairs_hook=OrderedDict)
        except ValueError:
            return False, "failed: https://dnsapi.cn/Record.Create return a invalid json: {content}".format(content=content)

        try:
            status = content["status"]
            code = status["code"]
            message = status["message"]
        except KeyError:
            return False, u"failed: https://dnsapi.cn/Record.Create return a json without status or msg, content:{content}".format(content=content)

        if int(code) != 1:
            delete_line(line_auto_id)
            data = u"failed: https://dnsapi.cn/Record.Create code not eq 1, message:{message}".format(message=message)
            mark_task_del(task_id, data)
            return False, data

        return content['record']['id'], None

    except requests.exceptions.Timeout:
        return False, "failed: https://dnsapi.cn/Record.Create timeout"

    except requests.exceptions.ConnectionError:
        return False, "failed: https://dnsapi.cn/Record.Create timeout"


def add_cloudxns_record(auth, domain_id, hostname, line_id, ip, ttl, task_id, line_auto_id):
    try:
        auth = json.loads(auth)
        api_key = auth["api_key"]
        secret_key = auth["secret_key"]
        api = Api(api_key=api_key, secret_key=secret_key)
        result = api.record_add(domain_id, hostname, ip, record_type='A', mx=None, ttl=ttl, line_id=line_id)
        result = json.loads(result)
        code = result['code']
        message = result['message']
        if int(code) != 1:
            delete_line(line_auto_id)
            mark_task_del(task_id, message)
            return False, message

        return result['record_id'], None

    except httplib.ResponseNotReady:
        return False, "timeout"

    except socket.error:
        return False, "ConnectionError"

def add_record(dns, auth, domain_id, hostname, line_id, ip, ttl, task_id, line_auto_id):
    if dns == "dnspod":
        return add_dnspod_record(auth, domain_id, hostname, line_id, ip, ttl,task_id, line_auto_id)

    elif dns == "cloudxns":
        return add_cloudxns_record(auth, domain_id, hostname, line_id, ip, ttl,task_id, line_auto_id)


def del_dnspod_record(auth, domain_id, record_id, task_id):
    auth = json.loads(auth)
    id = auth["id"]
    token = auth["token"]
    login_token = "{id},{token}".format(id=id, token=token)
    try:
        data = {"login_token":login_token,"format":"json","domain_id":domain_id,"record_id":record_id}
        headers = {"User-Agent":"python requests client/1.0.0(admin@centos.bz)"}
        r = requests.post("https://dnsapi.cn/Record.Remove",data=data,timeout=20,headers=headers)
        status_code = r.status_code
        if status_code != 200:
            return False, "failed: https://dnsapi.cn/Record.Remove return status code: {status_code}".format(status_code=status_code)

        content = r.content

        try:
            content = json.loads(content,object_pairs_hook=OrderedDict)
        except ValueError:
            return False, "failed: https://dnsapi.cn/Record.Remove return a invalid json: {content}".format(content=content)

        try:
            status = content["status"]
            code = status["code"]
            message = status["message"]
        except KeyError:
            return False, u"failed: https://dnsapi.cn/Record.Remove return a json without status or msg, content:{content}".format(content=content)

        if int(code) != 1:
            data = u"failed: https://dnsapi.cn/Record.Remove code not eq 1, message:{message}".format(message=message)
            mark_task_del(task_id, data)
            return False, 

        return True, None

    except requests.exceptions.Timeout:
        return False, "failed: https://dnsapi.cn/Record.Remove timeout"

    except requests.exceptions.ConnectionError:
        return False, "failed: https://dnsapi.cn/Record.Remove timeout"


def del_cloudxns_record(auth, domain_id, record_id, task_id):
    try:
        auth = json.loads(auth)
        api_key = auth["api_key"]
        secret_key = auth["secret_key"]
        api = Api(api_key=api_key, secret_key=secret_key)
        result = api.record_delete(record_id, domain_id)
        result = json.loads(result)
        code = result['code']
        message = result['message']
        if int(code) != 1:
            mark_task_del(task_id, message)
            return False, message

        return True, None

    except httplib.ResponseNotReady:
        return False, "timeout"

    except socket.error:
        return False, "ConnectionError"

def del_record(dns, auth, domain_id, record_id, task_id):
    if dns == "dnspod":
        return del_dnspod_record(auth, domain_id, record_id, task_id)

    elif dns == "cloudxns":
        return del_cloudxns_record(auth, domain_id, record_id, task_id)


def update_line_record_id(line_auto_id, record_id):
    statement = line.update().where( (line.c.id == line_auto_id)) .values(record_id=record_id)
    db.session.execute(statement)
    db.session.commit()
    db.session.close()

def delete_line(id):
    statement = line.delete().where( (line.c.id==id) )
    db.session.execute(statement)
    db.session.commit()
    db.session.close()

def main():

    sleep_time = 5
    # 添加记录
    task = Task.query.filter( (Task.type=="update_dns_record") & (Task.delflag == 0) & ( Task.state != "success")).first()
    if task is None:
        db.session.close()
        return sleep_time

    sleep_time = 1
    task_id = task.id
    value = task.value
    data = json.loads(value)
    action = data['action']
    line_group_id = data['line_group_id']
    dns = data['dns']
    auth = data['auth']
    domain_id = data['domain_id']
    domain = data['domain']
    hostname = data['hostname']
    ttl = data['ttl']

    mark_task_start(task_id, 1)
    title = "update_dns_record {domain}"
    user_id = 1
    type = "update_dns_record"
    res = domain
    level = "failed"

    if action == "add":
        line_auto_id = data["id"]
        ip = data["ip"]
        line_id = data['line_id']
        node_id = data['node_id']
    
        record_id, err = add_record(dns, auth, domain_id, hostname, line_id, ip, ttl,task_id,line_auto_id)
        if err is None:
            title = u"add {dns} {hostname}.{domain} {ip} line_id:{line_id} ttl:{ttl} record".format(dns=dns,hostname=hostname,domain=domain,ip=ip, line_id=line_id, ttl=ttl)
            data = None
            level = "success"
            make_msg(title, data, user_id, type, res, level)
            update_line_record_id(line_auto_id, record_id)
            mark_task_success(task_id, data)
        else:
            title = u"add {dns} {hostname}.{domain} record".format(dns=dns,hostname=hostname,domain=domain)
            data = err
            make_msg(title, data, user_id, type, res, level)
            mark_task_failed(task_id, data)
            sleep_time = 60

    elif action == "del":
        record_id = data['record_id']
        ok, err = del_record(dns, auth, domain_id, record_id, task_id)
        if err is None:
            title = u"delete {dns} {hostname}.{domain} record_id:{record_id} record".format(dns=dns,hostname=hostname,domain=domain,record_id=record_id)
            data = None
            level = "success"
            make_msg(title, data, user_id, type, res, level)
            mark_task_success(task_id, data)
        else:
            title = u"delete {dns} {hostname}.{domain} record_id:{record_id} record".format(dns=dns,hostname=hostname,domain=domain,record_id=record_id)
            data = err
            make_msg(title, data, user_id, type, res, level)
            mark_task_failed(task_id, data)
            sleep_time = 60

    db.session.close()
    return sleep_time

if __name__ == '__main__':
    main()