import sys
from Manifest import Manifest
from ProjectAnalizer import ProjectAnalizer
from os.path import dirname, basename, isdir, join, realpath

__author__ = 'Samuel Flores'

class ManifestAnalizer:

    def __init__(self, manifest_p, root=None):
        self.manifest = manifest_p

        if root:
            self.root = root
        else:
            try:
                self.root = self.locate_root()
            except EnvironmentError:
                print('cant find .repo dir', file=sys.stderr)
                sys.exit(-1)

        self.project_l = self.get_projects(manifest_p)
        self.analizer_l = []

        self.missing_buildfile = []
        self.missing_module = []

        for p in self.project_l:
            analizer = ProjectAnalizer(p, self.root)
            self.analizer_l.append(analizer)

    def get_summary(self):
        total = len(self.project_l)
        complete = len(self.get_complete())
        missing_file = len(self.get_missing_buildfile())

        ret = 'Total projects: ' + str(total)
        ret += '\nComplete: ' + str(complete)
        ret += '\nWith Android.mk but incomplete: ' + str(total-complete-missing_file)
        ret += '\nMissing Android.mk: ' + str(missing_file)

        return ret

    # TODO: optimize this
    def get_missing_buildfile(self):
        ret = []
        for pa in self.analizer_l:
            assert isinstance(pa, ProjectAnalizer)
            if not pa.buildFile:
                ret.append(pa)
        return ret

    def get_incomplete(self):
        ret = []
        for pa in self.analizer_l:
            assert isinstance(pa, ProjectAnalizer)
            if not pa.module_name and pa.buildFile:
                ret.append(pa)
        return ret

    def get_complete(self):
        ret = []
        for pa in self.analizer_l:
            assert isinstance(pa, ProjectAnalizer)
            if pa.module_name:
                ret.append(pa)
        return ret

    def get_analizer_for_project(self, project_name):
        ret = None
        for pa in self.analizer_l:
            assert isinstance(pa, ProjectAnalizer)
            if pa.project.name == project_name:
                ret = pa
                break

        return ret

    # look for ".repo" in parent directory
    # thanks to autopatch
    def locate_root(self):

        lookdir = realpath(dirname(self.manifest))
        while not isdir(join(lookdir, '.repo')):
            newlookdir = dirname(lookdir)
            if lookdir == newlookdir:
                # .repo not found
                raise EnvironmentError
            lookdir = newlookdir
        print('found repo top at', lookdir)
        return lookdir

    def get_projects(self, manifest_p):
        m = Manifest(manifest_p)
        return m.proj_list