#! /usr/bin/python3

import os
import sys
import json
import getpass
from modularitea.atom import Atom
from modularitea.progress_adapter import FetchProgressAdapter, InstallProgressAdapter
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Vte, GLib
import platform
import apt, apt_pkg

# PREFIX = "/opt/"
PREFIX = "/home/mnirfan/Projects/"
sys.path.append(PREFIX+"modularitea/")

user = 'mnirfan'
home = "/home/"+user+"/"
USER_MODULE_DIR = '/home/' + user + '/.modulaitea/modules/'
print("USER_MODULE_DIR", USER_MODULE_DIR)
# SYS_MODULE_DIR = '/opt/modularitea/modules/'
# USER_MODULE_DIR = PREFIX + 'modularitea/modules/'
SYS_MODULE_DIR = '/usr/share/modularitea/modules/'
print("SYS_MODULE_DIR", SYS_MODULE_DIR)

ARCH = 32

if platform.architecture()[0] == '64bit':
    ARCH = 64


class Module:
    module = None
    apt_atoms = []
    ppas = []
    http_atoms = []
    progressbar = None

    def __init__(self, module_name, progressbar, action_label, terminal, expander):
        self.terminal = terminal
        self.progressbar = progressbar
        self.action_label = action_label
        self.expander = expander
        if os.path.exists(USER_MODULE_DIR + module_name):
            with open(USER_MODULE_DIR + module_name + '/package.json') as data:
                self.module = json.load(data)
            print("module", module_name, "found in user dir")
        elif os.path.exists(SYS_MODULE_DIR + module_name):
            with open(SYS_MODULE_DIR + module_name + '/package.json') as data:
                self.module = json.load(data)
            print("module", module_name, "found in sys dir")
        else:
            print('Modul ' + module_name + " doesn't exist")
            # raise FileNotFoundError

        for atom in self.module['package']['atoms']:
            atom_temp = Atom(atom)
            print("found ", atom_temp.get_name())
            print(atom_temp.object['package']['preferred_source'])
            if atom_temp.object['package']['preferred_source'] == 'ubuntu_apt':
                self.apt_atoms.append(atom_temp)
                if "ppa" in atom_temp.object['package']['source']['ubuntu_apt']:
                    self.ppas.append(atom_temp.object['package']['source']['ubuntu_apt']['ppa'])
            elif atom_temp.object['package']['preferred_source'] == 'http_archive':
                self.http_atoms.append(atom_temp)
            else:
                raise AttributeError

        print('APT      :', self.apt_atoms)
        print('Download :', self.http_atoms)
        print('PPA      :', self.ppas)

        if not os.path.exists(home + ".modularitea/download"):