# -*- 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
        while ( i < len(self.__name) ):
            if ( self.__name[i] == ' ' ):
                while (self.__name[i] == ' ' ):
                    i += 1
                pl_dir_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.replace('__', '_').strip('_')
    

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

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

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


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'
    
    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')
    
    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(
                this_script_path,
                "../",
                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)
                    )
                )

    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)
