import os
import shutil
import subprocess
import sys

import dmgbuild

from .app import app


class macos(app):
    description = "Create a macOS app to wrap this project"

    def finalize_options(self):
        # Copy over all the options from the base 'app' command
        finalized = self.get_finalized_command('app')
        for attr in ('formal_name', 'organization_name', 'bundle', 'icon', 'download_dir', 'document_types','dmg'):
            if getattr(self, attr) is None:
                setattr(self, attr, getattr(finalized, attr))

        super(macos, self).finalize_options()

        # Set platform-specific options
        self.platform = 'macOS'
        self.support_project = "Python-Apple-support"

        if self.dir is None:
            self.dir = 'macOS'

        self.resource_dir = os.path.join(self.dir, '{}.app'.format(self.formal_name), 'Contents', 'Resources')

    def install_icon(self):
        shutil.copyfile(
            "%s.icns" % self.icon,
            os.path.join(self.resource_dir, '%s.icns' % self.distribution.get_name())
        )

        for tag, doctype in self.document_types.items():
            shutil.copyfile(
                "%s.icns" % doctype['icon'],
                os.path.join(self.resource_dir, "%s-%s.icns" % (self.distribution.get_name(), tag))
            )

    def install_splash(self):
        raise RuntimeError("macOS doesn't support splash screens.")

    @property
    def launcher_header(self):
        """
        Override the shebang line for launcher scripts
        """
        # https://stackoverflow.com/a/36160331
        pyexe = '../Resources/python/bin/python{}'.format(3 if sys.version_info.major == 3 else '')
        return '#!/bin/sh\n'\
               '"exec" "`dirname $0`/{}" "$0" "$@"\n'.format(pyexe)

    @property
    def launcher_script_location(self):
        macos_dir = os.path.abspath(os.path.join(self.resource_dir, '..', 'MacOS'))
        return macos_dir

    def build_app(self):
        print("Building DMG file...")
        dmg_name = self.formal_name.replace(' ', '_') + '.dmg'
        dmg_path = os.path.join(os.path.abspath(self.dir), dmg_name)
        dmgbuild.build_dmg(filename=dmg_path, volume_name=self.formal_name)

        return True

    def post_build(self):
        pass

    def start_app(self):
        print("Starting %s.app" % (self.formal_name))
        subprocess.Popen([
                'open', '%s.app' % self.formal_name
            ],
            cwd=os.path.abspath(self.dir)
        ).wait()

@@ -328,19 +328,17 @@
     
-for attr in
+options =
  ('f
@@ -370,16 +370,35 @@
 n_name',
+%0A                  
  'bundle
@@ -444,15 +444,37 @@
 pes'
-,'dmg')
+)%0A        for attr in options
 :%0A  
@@ -812,17 +812,16 @@
 'macOS'%0A
-%0A
         
@@ -825,28 +825,28 @@
    self.
-resource_dir
+app_location
  = os.pa
@@ -879,16 +879,29 @@
 .format(
+%0A            
 self.for
@@ -909,16 +909,119 @@
 al_name)
+)  # Location of the .app file%0A%0A        self.resource_dir = os.path.join(%0A            self.app_location
 , 'Conte
@@ -1144,81 +1144,30 @@
     
-os.path.join(self.resource_dir, '%25s.icns' %25 self.distribution.get_name())
+self.icon_install_path
 %0A   
@@ -1367,16 +1367,45 @@
 .icns%22 %25
+%0A                            
  (self.d
@@ -1777,16 +1777,29 @@
 .format(
+%0A            
 3 if sys
@@ -2021,16 +2021,29 @@
 abspath(
+%0A            
 os.path.
@@ -2210,26 +2210,8 @@
 name
-.replace(' ', '_')
  + '
@@ -2285,16 +2285,154 @@
 g_name)%0A
+        settings = %7B'files': %5Bself.app_location%5D,%0A                    'symlinks': %7B'Applications': '/Applications'%7D%0A                    %7D%0A
         
@@ -2468,16 +2468,43 @@
 mg_path,
+%0A                          
  volume_
@@ -2524,18 +2524,63 @@
 mal_name
+,%0A                           settings=settings
 )
-%0A
 %0A       
@@ -2751,20 +2751,16 @@
         
-    
 'open', 
@@ -2787,20 +2787,16 @@
 al_name%0A
-    
         

Insert files into created dmg