import kivy
import random
from kivy.app import App
from kivy.core.window import Window
import glob
from jnius import cast
from jnius import autoclass
import os
from commands import *
from utils import *
from kivy.lang import Builder
from kivy.metrics import metrics
from kivy.uix.floatlayout import FloatLayout
from unicodedata import category

Environment=autoclass("android.os.Environment")
PythonActivity = autoclass('org.renpy.android.PythonActivity')
Intent = autoclass('android.content.Intent')
Uri = autoclass('android.net.Uri')
ComponentName=autoclass('android.content.ComponentName')
ActivityInfo= autoclass("android.content.pm.ActivityInfo")
PackageInfo= autoclass("android.content.pm.PackageInfo")
PackageManager= autoclass("android.content.pm.PackageManager")
Cursor=autoclass("android.database.Cursor")


AsyncTask=autoclass("com/example/asynctask/MyAsyncTask")

Environment=autoclass("android.os.Environment");
TimeUnit=autoclass("java.util.concurrent.TimeUnit")
intents=[]
intents_package_names=[]
commands=[]
categories=[]
extra_keys=[]
extra_types=[]
activity_actions=[]
flags=[]
path_txt="txts/"

with open(path_txt + "categories.txt") as f:
        categories = f.read().splitlines()

with open(path_txt + "extra_keys.txt") as f:
        extra_keys = f.read().splitlines()

with open(path_txt + "extra_types.txt") as f:
        extra_types = f.read().splitlines()

with open(path_txt + "flags.txt") as f:
        flags = f.read().splitlines()
with open(path_txt + "activity_actions.txt") as f:
        activity_actions = f.read().splitlines()
for i in range(len(flags)):
    index_fl = flags[i].index(':')
    if index_fl > 0:
        flags[i] = flags[i][index_fl+1:]
# get_default_values("/data/local/tmp/txts/",categories,extra_keys,extra_types,flags)


def log_in_logcat(log): 
    log_command = "log -p f -t %s" % (str(log))
    output = getoutput(log_command)

#parse all lines in a seed file and create intents/broadcast arrays
def parse_seed_line_command(command):
        adb_params = command.split(" ");   
        package=adb_params[adb_params.index("-n")+1]
        packageName=package.split("/")
        intents_package_names.append(packageName[1])
        if (command.find('broadcast')>-1):           
            intent_type=0
        else:   
            intent_type=1         
            action=adb_params[adb_params.index("-a")+1]
            s=adb_params[adb_params.index("-f")+2]
            flag=int(s, 0)
            category=adb_params[adb_params.index("-c")+1]
            data=Uri.parse(adb_params[adb_params.index("-d")+1])
            extra_type=adb_params[adb_params.index("-e")+1]
            extra_string=adb_params[adb_params.index("-e")+2]
            extra_value=adb_params[adb_params.index("-e")+3]
        
        intent = Intent()
        intent.setComponent(ComponentName(packageName[0],packageName[1]))      
        if (intent_type==0):
            intents.append(intent)
        else:
            intent.setAction(action)
            intent.addCategory(category)
            intent.setData(data)
            intent.setFlags(flag)   
            if extra_type=="boolean":
                if extra_value=="true":
                    intent.putExtra(extra_string, "true")
                else:
                    intent.putExtra(extra_string, "false")
            elif extra_type=="string":
                intent.putExtra(extra_string, extra_value)
            elif extra_type=="int":
                intent.putExtra(extra_string, int(extra_value))
            intents.append(intent)                                               
        return intent_type
 
config = PythonActivity.mActivity.getResources().getConfiguration() 

 
            
Builder.load_file("AppLayout.kv")


class Bifuz(FloatLayout):
#     Window.clearcolor = (0,1,1,0)
    def fontscale(self):
        dpi = metrics.dpi_rounded
        if dpi < 140:
            return 1
        elif dpi < 200:
            return 2
        elif dpi < 280:
            return 2.5
        return 3
    
    
#  
# #  Generate Broadcast Intent calls
#  

     #get all packages and activities for Broadcast
    def get_all_Broadcast_packages(self):
        arrayList=[]
        mypackList=[]
        pm = PythonActivity.mActivity.getPackageManager()
        mypackList=pm.getInstalledPackages(PackageManager.GET_RECEIVERS).toArray()  
        for pack in mypackList:
            arrayList.append(pack.packageName)
            
        self.s41.values = arrayList              
        self.s41.bind(text=self.generate_intents_Receivers)
             
        
    def generate_intents_Receivers(self,spinner,text):
        output = getoutput("logcat -c") 
        PackListReceiver=[]
        receivers=[]
        pm = PythonActivity.mActivity.getPackageManager()
        PackListReceiver=pm.getPackageInfo(text, PackageManager.GET_RECEIVERS).receivers
        
        if (PackListReceiver is not None):
            for pack in PackListReceiver:
                packageName=text
                packageClass=pack.name
                command=' am broadcast -n ' + packageName +'/' + packageClass
                PythonActivity.toastError('BIFUZ_BROADCAST ' + command)
                task=AsyncTask(PythonActivity.mActivity) 
                task.execute("broadcast",packageName,packageClass,command)
                receivers.append(packageClass)
                
                path="/sdcard/test/"
                for filename in glob.glob(os.path.join(path, '*.sh')):
                    file_path=filename.split("/sdcard/test/")
                    if file_path[1] in self.s1.values:
                        ok=False
                    else:    
                        self.s1.values.append(file_path[1])
        else:           
            PythonActivity.toastError("No receivers found for this app")         
    
#     
# # Generate Fuzzed Intent calls  
#      
    #get all Broadcast packages
    def get_all_Activities_packages(self):
        arrayList=[]
        mypackList=[]
        pm = PythonActivity.mActivity.getPackageManager()
        mypackList=pm.getInstalledPackages(PackageManager.GET_ACTIVITIES).toArray()       
        for pack in mypackList:
            arrayList.append(pack.packageName)
        self.s31.values = arrayList              
        self.s31.bind(text=self.generate_intents_Activities)        
          
     #get all packages and activities
    def generate_intents_Activities(self,spinner, text):
        output = getoutput("logcat -c") 
        PackListActivities=[]
        activities=[]
        pm = PythonActivity.mActivity.getPackageManager()
        PackListActivities=pm.getPackageInfo(text, PackageManager.GET_ACTIVITIES).activities 
        if (PackListActivities is not None):
            for pack in PackListActivities:
                packageName=text
                packageClass=pack.name
                activities.append(packageClass)