// @flow

import path from 'path';
import fs from 'fs';

import { parseString, Builder } from 'xml2js';

import generator from './generator.js';

const ANDROID_ROOT_PATH = path.join('android', 'app', 'src', 'main');
const ANDROID_MANIFEST_FILE = path.join(ANDROID_ROOT_PATH, 'AndroidManifest.xml');

const generateActivityFile = (packageName: string) => {
  const fileName = path.join(ANDROID_ROOT_PATH, 'java', ...packageName.split('.'), 'SplashActivity.java');
  console.log('[SPLASHSCREEN] Writing: ' + fileName);
  fs.writeFileSync(fileName,
`package ${packageName};

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class SplashActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}`
  );
};

const updateManifest = (json?: Object) => {
  const { manifest } = json;
  const { application } = manifest;
  const { activity, $ } = application.find(node => node.$);
  $['android:theme'] = '@style/SplashTheme';
  const newJson = json;
  const newActivity = activity
    .map(activity => {
      if (activity.$['android:label']) {
        activity.$['android:name'] = '.SplashActivity';
      }
      return activity;
    })
    .filter(activity => activity.$['android:name'] !== '.MainActivity');
  newActivity.push({
    $: {
      'android:name': '.MainActivity',
      'android:screenOrientation': $['android:screenOrientation'] || 'unspecified',
      'android:configChanges': 'keyboard|keyboardHidden|orientation|screenSize',
    },
  });
  newJson.manifest.application.find(node => node.$).activity = newActivity;
  const builder = new Builder();
  console.log('[SPLASHSCREEN] Updating: ' + ANDROID_MANIFEST_FILE);
  fs.writeFileSync(ANDROID_MANIFEST_FILE, builder.buildObject(newJson));
}

export default (splashScreenPath: string, dockIconPath: string) => {
  fs.readFile(ANDROID_MANIFEST_FILE, (e?: Error, xml?: Object) => {
    if (e) {
      console.error(e);
    }
    parseString(xml, (e?: Error, json?: Object) => {
      if (e) {
        console.error(e);
      }
      updateManifest(json);
      generateActivityFile(json.manifest.$['package']);
    });
  });
  generator(splashScreenPath, dockIconPath);
};

@@ -291,16 +291,105 @@
 t.xml');
+%0Aconst ANDROID_STYLES_FILE = path.join(ANDROID_ROOT_PATH, 'res', 'values', 'styles.xml');
 %0A%0Aconst 
@@ -1169,28 +1169,26 @@
 manifest;%0A  
-cons
+le
 t %7B activity
@@ -1230,15 +1230,73 @@
 de.$
-);%0A  $%5B
+ && node.$%5B'android:name'%5D === '.MainApplication');%0A  $ = %7B...$, 
 'and
@@ -1306,19 +1306,17 @@
 d:theme'
-%5D =
+:
  '@style
@@ -1332,46 +1332,14 @@
 eme'
+%7D
 ;%0A  
-const newJson = json;%0A  const newA
+a
 ctiv
@@ -1586,20 +1586,17 @@
 ty');%0A  
-newA
+a
 ctivity.
@@ -1832,84 +1832,8 @@
 %7D);%0A
-  newJson.manifest.application.find(node =%3E node.$).activity = newActivity;%0A
   co
@@ -1995,20 +1995,600 @@
 ect(
-newJ
+json));%0A%7D;%0A%0Aconst updateStyles = (json?: Object) =%3E %7B%0A  const %7B resources %7D = json;%0A  let %7B style = %5B%5D %7D = resources;%0A  style = style%0A    .filter(style =%3E style.$%5B'name'%5D !== 'SplashTheme');%0A  style.push(%7B%0A    $: %7B%0A      'name': 'SplashTheme',%0A      'parent': 'Theme.AppCompat.Light.NoActionBar',%0A    %7D,%0A    item: %5B%7B%0A      $: %7B%0A        'name': 'android:windowBackground',%0A      %7D,%0A      _: '@drawable/splash',%0A    %7D%5D,%0A  %7D);%0A  const builder = new Builder();%0A  console.log('%5BSPLASHSCREEN%5D Updating: ' + ANDROID_STYLES_FILE);%0A  fs.writeFileSync(ANDROID_STYLES_FILE, builder.buildObject(j
 son));%0A%7D
 %0A%0Aex
@@ -2583,16 +2583,17 @@
 son));%0A%7D
+;
 %0A%0Aexport
@@ -2896,16 +2896,16 @@
 (json);%0A
-
       ge
@@ -2966,16 +2966,267 @@
 ;%0A  %7D);%0A
+  fs.readFile(ANDROID_STYLES_FILE, (e?: Error, xml?: Object) =%3E %7B%0A    if (e) %7B%0A      console.error(e);%0A    %7D%0A    parseString(xml, (e?: Error, json?: Object) =%3E %7B%0A      if (e) %7B%0A        console.error(e);%0A      %7D%0A      updateStyles(json);%0A    %7D);%0A  %7D);%0A
   genera

Add SplashTheme style to Android styles.xml file