#!/usr/bin/python
import os
import sys
import argparse
import shutil
from subprocess import call
import zipfile
import subprocess

if sys.version_info >= (3,):
    import urllib.request as urllib2
    import urllib.parse as urlparse
else:
    import urllib2
    import urlparse


ROOT = os.path.dirname(os.path.abspath(__file__))


def unzipFile(filename):
    zfile = zipfile.ZipFile(filename)
    for name in zfile.namelist():
        (dirname, filename) = os.path.split(name)
        print "Decompressing " + filename + " on " + dirname
        zfile.extract(name)


def copytree(src, dst, symlinks=False, ignore=None):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            shutil.copytree(s, d, symlinks, ignore)
        else:
            shutil.copy2(s, d)

# setup opencv


def download_file(url, desc=None):
    u = urllib2.urlopen(url)

    scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
    filename = os.path.basename(path)
    if not filename:
        filename = 'downloaded.file'
    if desc:
        filename = os.path.join(desc, filename)

    with open(filename, 'wb') as f:
        meta = u.info()
        meta_func = meta.getheaders if hasattr(
            meta, 'getheaders') else meta.get_all
        meta_length = meta_func("Content-Length")
        file_size = None
        if meta_length:
            file_size = int(meta_length[0])
        print("Downloading: {0} Bytes: {1}".format(url, file_size))

        file_size_dl = 0
        block_sz = 8192
        while True:
            buffer = u.read(block_sz)
            if not buffer:
                break

            file_size_dl += len(buffer)
            f.write(buffer)

            status = "{0:16}".format(file_size_dl)
            if file_size:
                status += "   [{0:6.2f}%]".format(
                    file_size_dl * 100 / file_size)
            status += chr(13)

    return filename


def downloadPrebuiltOpencv(prefix='.', out_prefix='.', version='3.1.0'):
    OPENCV_PREBUILT_URL = 'http://netix.dl.sourceforge.net/project/opencvlibrary/opencv-android/{0}/OpenCV-{0}-android-sdk.zip'.format(
        version)
    OPENCV_ARCHIVE = 'OpenCV-{0}-android-sdk.zip'.format(version)
    OPENCV_UNZIP_DIR = 'OpenCV-android-sdk'
    OPENCV_OUT_PATH = 'opencv'

    OPENCV_UNZIP_DIR = os.path.join(prefix, OPENCV_UNZIP_DIR)
    OPENCV_OUT_PATH = os.path.join(out_prefix, OPENCV_OUT_PATH)
    OPENCV_UNZIP_SDK_DIR = os.path.join(OPENCV_UNZIP_DIR, 'sdk', 'native')

    print  'OPENCV_PREBUILT_URL  %s' %OPENCV_PREBUILT_URL
    print  'OPENCV_ARCHIVE %s' %OPENCV_ARCHIVE
    print  'OPENCV_OUT_PATH %s' %OPENCV_OUT_PATH
	
    if not os.path.isdir(OPENCV_UNZIP_DIR):
        currDir = os.getcwd()
        os.chdir(prefix)
        if not os.path.exists(OPENCV_ARCHIVE):
            download_file(OPENCV_PREBUILT_URL)

        unzipFile(OPENCV_ARCHIVE)
        os.chdir(currDir)

    if not os.path.exists(OPENCV_OUT_PATH):
        os.makedirs(OPENCV_OUT_PATH)

    # Remove it if it exist
    shutil.rmtree(OPENCV_OUT_PATH)
    copytree(OPENCV_UNZIP_SDK_DIR, OPENCV_OUT_PATH)


def sync_submodules():
    print '---------------- Start syncing submodules ----------------'
    # Fetch submodules
    global ROOT
    os.chdir(ROOT)
    call(['git', 'submodule', 'update', '--init', '--recursive'])

    print 'download prebuilt opencv for android'
    prebuilt_path = os.path.join(ROOT, 'third_party')
    prebuilt_opencv_out = prebuilt_path
    downloadPrebuiltOpencv(
        prefix=prebuilt_path, out_prefix=prebuilt_opencv_out)
    print '---------------- End   syncing submodules ----------------'


def main(argv):
    sync_submodules()

if __name__ == '__main__':
    main(sys.argv[1:])
