# -*- coding: utf-8 -*-
import os
import ConfigParser

this_script_path =  os.path.dirname(__file__)

class QGISPlugin(object):
    def __init__(self):
        self.__md_filename = os.path.join(
            this_script_path,
            "metadata.txt"
        )
        if not os.path.exists(self.__md_filename):
            raise ValueError("File metadata.txt not found")

        config = ConfigParser.ConfigParser()
        config.read([self.__md_filename])

        self.__name = config.get('general', 'name').strip()
        self.__version = config.get('general', 'version')
        
        self.__pack_name = self.__generate_plugin_pack_name()

    def __generate_plugin_pack_name(self):
        pl_dir_name = ""
        
        i = 0
        if ( self.__name.find(' ') > 0 ):
            while ( i < len(self.__name) ):
                if ( self.__name[i] == ' ' ):
                    while (self.__name[i] == ' ' ):
                        i += 1
                    pl_dir_name += '_'

                pl_dir_name += self.__name[i].lower()
                i += 1
        else:
            while ( i < len(self.__name) ):
                if ( self.__name[i].isupper() ):
                    pl_dir_name += '_'
                    while( self.__name[i].isupper() ):
                        pl_dir_name += self.__name[i].lower()
                        i += 1

                pl_dir_name += self.__name[i]
                i += 1

        return pl_dir_name.strip('_')
    

    @property
    def pack_name(self):
        return self.__pack_name
    

    @property
    def name(self):
        return self.__name


    @property
    def version(self):
        return self.__version


    @property
    def i18nPath(self):
        return os.path.join(this_script_path, "i18n")

if __name__ == "__main__":
    import json
    import pprint
    import shutil
    import zipfile
    import subprocess
    import argparse

    parser = argparse.ArgumentParser(description='Make qgis python plugin.')
    
    install_cmd_name = 'install'
    pack_cmd_name = 'pack'
    make_cmd_name = 'make'
    ts_cmd_name = 'ts'
    qm_cmd_name = 'qm'
    
    subparsers = parser.add_subparsers(help='commands help', dest='command')
    
    parser_install = subparsers.add_parser(install_cmd_name, help='Install plugin to dir')
    parser_install.add_argument('install_dir', type=unicode, help='Destanation dir')
    
    parser_pack = subparsers.add_parser(pack_cmd_name, help='Make zip with plugin')
    #parser_make = subparsers.add_parser(make_cmd_name, help='Make all uis, rcs, i18 and other')
    
    parser_ts = subparsers.add_parser(ts_cmd_name, help='Make ts file from all files in plugin')
    parser_ts.add_argument('black_list', type=unicode, help='list of exclude dirs and files')

    parser_qm = subparsers.add_parser(qm_cmd_name, help='Make qm files from qm file in ./i18n dir')
    
    args = parser.parse_args()
    
    pl = QGISPlugin()
    

    def install(install_dir, plugin_dir_name):
        print "install ..."

        if not os.path.exists(install_dir):
            print "Directory %s not found" % install_dir
            return

        install_dir = os.path.join(install_dir, plugin_dir_name)

        def copytree(src, dst):
            if not os.path.exists(dst):
                os.makedirs(dst)
            for item in os.listdir(src):
                s = os.path.join(src, item)
                d = os.path.join(dst, item)
                if os.path.isdir(s):
                    copytree(s, d)
                else:
                    if not os.path.exists(d) or os.stat(s).st_mtime - os.stat(d).st_mtime > 1:
                        print "install %s" % d
                        shutil.copy2(s, d)

        copytree(this_script_path, install_dir)


    def pack(plugin_dir_name, plugin_version):
        print "packing ..."
        zipFile = zipfile.ZipFile(
            os.path.join(
                os.getcwd(),
                plugin_dir_name + "." + plugin_version + ".zip"
            ),
            'w'
        )
        ignore_list = (
            '.gitignore',
            '.pyc',
            '.ts',
            '.qrc',
        )
        for root, dirs, files in os.walk(this_script_path):
            if root.find('.git') != -1:
                continue

            for f in files:
                if f.endswith(ignore_list):
                    continue
                filename = os.path.join(root, f)
                zipFile.write(
                    filename,
                    os.path.join(
                        plugin_dir_name,
                        os.path.relpath(filename, this_script_path)
                    )
                )


    def generate_ts(black_list):
        print "generate ts ..."
        if not os.path.exists(pl.i18nPath):
            os.makedirs(pl.i18nPath)

        ts_file = os.path.join(
            pl.i18nPath,
            "%s_ru.ts" % pl.pack_name
        )

        white_list = (
            '.py',
            '.ui',
        )

        target_files = []
        for root, dirs, files in os.walk(this_script_path):
            if root.find('.git') != -1:
                continue

            if root.find(black_list) != -1:
                continue

            for f in files:
                if not f.endswith(white_list):
                    continue
                filename = os.path.join(root, f)
                target_files.append(filename)

        cmd = ['pylupdate4']
        cmd.extend(target_files)
        cmd.append("-ts")
        cmd.append(ts_file)

        pprint.pprint(cmd)
        subprocess.call(cmd, shell=True)


    def make_qm():
        print "making ts ..."
        i18n_files = [f for f in os.listdir(pl.i18nPath) if os.path.splitext(f)[1] == ".ts"]

        for i18n_file in i18n_files:
            ts_file = os.path.join(pl.i18nPath, i18n_file)
            print "Process %s ..." % ts_file
            subprocess.call([
                'lrelease',
                ts_file
            ])

    if args.command == install_cmd_name:
        install(args.install_dir, pl.pack_name)
    
    if args.command == pack_cmd_name:
        pack(pl.pack_name, pl.version)

    if args.command == ts_cmd_name:
        generate_ts(args.black_list)

    if args.command == qm_cmd_name:
        make_qm()


