#!/usr/bin/env python
#coding: utf-8
#by yangbin at 2018.11.28
from __future__ import print_function
import os
import sys
import json
import zipfile

from .conf import *
from .swagger import *
from .helper import *
from .version import version
from .service import new_srv_code
from .cmdmodel import CmdModel

if M2C_VERSION == 'v4':
    from .apimodel_v4 import ApiModelV4 as ApiModel
    from .swagger import genSwaggerGwGoV4

if IS_PY3():
    from urllib.request import urlretrieve
else:
    from urllib import urlretrieve


def swaggerhtml(apimodelPath):
    from .swagger3 import genSwaggerContent
    yaml = genSwaggerContent(apimodelPath)
    return yaml

def goswagger3():
    docpath = os.path.join(GOPHER_DIR, 'ak/gw/swagger.yaml')
    godocpath = os.path.join(GOPHER_DIR, 'ak/gw/swagger.go')
    from .swagger3 import genSwaggerYaml, genSwaggerGwGo
    if M2C_VERSION == 'v4':
        docpath = SWAGGER_YAML_PATH
        godocpath = SWAGGER_PATH
        from .swagger3 import genSwaggerGwGoV4 as genSwaggerGwGo

    genSwaggerYaml(docpath)
    genSwaggerGwGo(godocpath)
    print(Color.green('Gen %s done.' % docpath))
    print(Color.green('Gen %s done.' % godocpath))
 
def goswagger():
    config = {
        "name": "myapp",
        "version": "0.0.1",
        "description": "myapp api doc",
        "title": "myapp api doc",
        "url": "https://myapp.com"
    }

    if os.path.exists('dev.yaml'):
        try:
            from yaml import load, Loader
            app = load(open('dev.yaml'), Loader)
            config['name'] = app['name']
            config['description'] = app['apiDoc']['desc']
            config['title'] = app['apiDoc']['title']
            config['url'] = app['apiDoc']['url']
        except:
            pass
    url = config['url']
    
    docpath = os.path.join(GOPHER_DIR, 'ak/gw/swagger.go')
    genSwaggerGwGo(docpath, url, config['title'], config['description'], config['version'])
    print(Color.green('Gen goswagger to %s done.' % docpath))
    
def goapidoc():
    lines = open(APIMODEL_PATH, 'rb').readlines()
    if IS_PY3():
        lines = list(map(lambda x: x.decode('utf-8'), lines))
    apiModel = ApiModel.fromLines(lines)
    doc = apiModel.apiDoc()
    docpath = os.path.join(APIDOC_DIR, 'doc.go')
    writeCode(docpath, doc)
    print(Color.green('Gen api doc to %s done.' % docpath))

def apicode():
    lines = open(APIMODEL_PATH, 'rb').readlines()
    if IS_PY3():
        lines = list(map(lambda x: x.decode('utf-8'), lines))
    apiModel = ApiModel.fromLines(lines)
    apiModel.genApiCode()
    update_m2c(version, M2C_VERSION)
    print(Color.green('Gen api code done.'))
    print(Color.red('不要修改包含<// Code generated by m2c. DO NOT EDIT.> 头的自动生成文件, 会被覆盖!!!'))

def apicodev2():
    lines = open(APIMODEL_PATH, 'rb').readlines()
    if IS_PY3():
        lines = list(map(lambda x: x.decode('utf-8'), lines))
    apiModel = ApiModel.fromLines(lines)
    apiModel.genApiCodeV2()
    update_m2c(version, M2C_VERSION)
    print(Color.green('Gen api code done.'))
    print(Color.red('不要修改包含<// Code generated by m2c. DO NOT EDIT.> 头的自动生成文件, 会被覆盖!!!'))

def objcode():
    lines = open(OBJMODEL_PATH, 'rb').readlines()
    if IS_PY3(): # py2 vs py3
        lines = list(map(lambda x: x.decode('utf-8'), lines))
    objModel = ObjModel.fromLines(lines)
    objModel.checkObjCode()
    if M2C_VERSION == 'v4':
        objModel.genObjCodeV4()
    else:
        objModel.genObjCode()
    update_m2c(version, M2C_VERSION)
    print(Color.green('Gen object code done.'))
    print(Color.red('不要修改包含<// Code generated by m2c. DO NOT EDIT.> 头的自动生成文件, 会被覆盖!!!'))

def pubm2czip(v='0.0.1'):
    name = 'm2c-%s.zip' % v
    output = os.path.join(BUILD_DIST, name)
    tar = 'git archive --format zip --output %s release/%s' % (output, v)
    assert os.system(tar) == 0, 'archive %s failed!' % output
    up = 's3cmd put %s s3://dat-pub/m2c/%s' % (output, name)
    assert os.system(up) == 0, 'run %s failed!' % up
    print(Color.green('pub m2c %s success!' % name))

def check_m2c():
    if is_m2c():
        return
    print(Color.red("It's not m2c project, init first!!!"))
    print(Color.green('Run: m2c -h for a help'))
    print(Color.green('Run: mkdir <your-project-name> to create an empty project dir'))
    print(Color.green('Run: cd <your-project-name> enter your project dir'))
    print(Color.green('Run: m2c init'))
    os._exit(-1)


def show_m2c():
    data = open('.m2c').read()
    print(json.dumps(json.loads(data), indent=2))

def init(git=''):
    if os.path.exists('.m2c'):
        print(Color.red("It's already m2c project"))
        show_m2c()
        os._exit(-1)
    
    if len(os.listdir('.')) != 0:
        print(Color.red('Current dir not empty, create your project dir!'))

    project_name = os.path.basename(os.getcwd())
    print(Color.green('Start init...'))
    print(Color.green('Project name: %s' % project_name))

    if git != '':
        print(Color.green('Clone from %s' % git))
        os.system('git clone %s .' % git)
    else:
        m2c_work_dir = '__m2c__'
        m2c_zip_path = os.path.join(m2c_work_dir, M2C_PROJECT_INIT_NAME)
        os.mkdir(m2c_work_dir)
        zipurl = M2C_PROJECT_INIT_URL
        if M2C_VERSION == 'v4':
            zipurl = M2C_PROJECT_INIT_URL_V4
        urlretrieve(zipurl, m2c_zip_path)
        print(Color.green('Download %s success!' % zipurl))
        zip_m2c = zipfile.ZipFile(m2c_zip_path, 'r')
        zip_m2c.extractall('.')
        zip_m2c.close()
        os.system('rm -rf %s' % m2c_work_dir)

    cfg = {
        'name': project_name,
        '__version__': version,
        '__cliversion__': M2C_VERSION,
        '__msg__': 'this is m2c init record file, keep this here!',
    }
    writeCode('.m2c', json.dumps(cfg, indent=2))
    sed_file(APP_DEV_CONFIG_FILE, 'name: "gop"\n', 'name: "%s"\n' % project_name) # update project name
    print(Color.green('m2c project %s init success!' % project_name))

def gen_service(name, force=False):
    srv_dir = os.path.join(SERVICE_DIR, name)
    srv_path = os.path.join(srv_dir, '%s.go' % name)
    srv_init_path = os.path.join(srv_dir, 'init.go')
    if os.path.exists(srv_init_path) and not force:
        print(Color.red('%s already exists' % srv_init_path))
        os._exit(-1)

    init_code, srv_code = new_srv_code(name)
    writeCode(srv_init_path, init_code)
    writeCode(srv_path, srv_code)
    os.system('gofmt -w %s/service/%s' % (MOD, name))
    print(Color.green('init service %s done' % name))


def cmdcode():
    lines = open(CMDMODEL_PATH, 'rb').readlines()
    if IS_PY3():
        lines = list(map(lambda x: x.decode('utf-8'), lines))
    cmdModel = CmdModel.fromLines(lines)
    cmdModel.genCmdCode()
    print(Color.green('Gen cmd code done.'))
