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

from .conf import *
from .swagger import *
from .helper import *
from .version import version

def openapi():
    config = {
        "name": "myapp",
        "version": "0.0.1",
        "description": "myapp api doc",
        "title": "myapp api doc",
        "url": "https://myapp.com/api"
    }

    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'].lstrip('https://').lstrip('http://')
    
    docpath = os.path.join(APIDOC_DIR, 'swagger.yaml')
    genSwaggerYaml(docpath, url, config['title'], config['description'], config['version'])
    print Color.green('Gen swagger.yaml to %s done.' % docpath)
 
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'].lstrip('https://').lstrip('http://')
    
    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()
    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()
    apiModel = ApiModel.fromLines(lines)
    apiModel.genApiCode()
    update_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()
    objModel = ObjModel.fromLines(lines)
    objModel.checkObjCode()
    objModel.genObjCode()
    update_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 is_m2c():
    return os.path.exists('.m2c')

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():
    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)

    m2c_work_dir = '__m2c__'
    m2c_zip_path = os.path.join(m2c_work_dir, M2C_PROJECT_INIT_NAME)
    os.mkdir(m2c_work_dir)
    urllib.urlretrieve(M2C_PROJECT_INIT_URL, m2c_zip_path)
    print Color.green('Download %s success!' % M2C_PROJECT_INIT_URL)
    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,
        '__msg__': 'this is m2c init record file, keep this here!',
    }
    open('.m2c', 'wb').write(json.dumps(cfg, indent=2))
    print Color.green('m2c project %s init success!' % project_name)
