import time
import re

from cliff.command import Command

from . import common
from .config import get_final_config


class Submit(Command):
    'Submit an entry to a specific competition.'

    def get_parser(self, prog_name):
        parser = super(Submit, self).get_parser(prog_name)

        parser.add_argument('entry', help='entry file')

        parser.add_argument('-m', '--message', help='message')
        parser.add_argument('-c', '--competition', help='competition')
        parser.add_argument('-u', '--username', help='username')
        parser.add_argument('-p', '--password', help='password')

        return parser

    def take_action(self, parsed_args):
        config = get_final_config(parsed_args)

        username = config.get('username', '')
        password = config.get('password', '')
        competition = config.get('competition', '')

        browser = common.login(username, password)
        base = 'https://www.kaggle.com'
        competition_url = '/'.join([base, 'c', competition])
        submit_url = '/'.join([competition_url, 'submissions', 'attach'])

        entry = parsed_args.entry
        message = parsed_args.message

        competition_page = browser.get(competition_url)
        submit_page = browser.get(submit_url)

        if submit_page.status_code == 404:
            print('competition not found')
            return

        team_id = re.search(
            '"team":{"id":(?P<id>\d+)',
            str(competition_page.soup)
        ).group(1)

        submit_form = submit_page.soup.find(id='submission-form')
        submit_form.find(
            'input', {
                'name': 'SubmissionUpload'
            }
        )['value'] = entry

        if message:
            submit_form.find(
                'textarea', {
                    'name': 'SubmissionDescription'
                }
            ).insert(0, message)

        browser.submit(submit_form, submit_page.url)

        status_url = (
            'https://www.kaggle.com/'
            'c/{}/submissions/status.json'
            '?apiVersion=1&teamId={}'.format(competition, team_id)
        )

        while True:
            status = browser.get(status_url).json()
            if status['submissionStatus'] == 'pending':
                time.sleep(1)
                continue
            elif status['submissionStatus'] == 'complete':
                print(status['publicScoreFormatted'])
                break
            else:
                print('something went wrong')
                break

@@ -1,12 +1,22 @@
+import os%0A
 import time%0A
@@ -24,16 +24,28 @@
 mport re
+%0Aimport json
 %0A%0Afrom c
@@ -1037,24 +1037,110 @@
 n%5D)%0A        
+file_form_submit_url = '/'.join(%5Bbase, 'blobs/inbox/submissions'%5D)%0A        entry_form_
 submit_url =
@@ -1182,19 +1182,13 @@
 sion
-s', 'attach
+.json
 '%5D)%0A
@@ -1317,24 +1317,25 @@
 on_url)%0A
+%0A
         
 submit_p
@@ -1330,64 +1330,22 @@
     
-submit_page = browser.get(submit_url)%0A%0A        if submit
+if competition
 _pag
@@ -1569,278 +1569,495 @@
     
-submit_form = submit_page.soup.find(id='submission-form')%0A        submit_form.find(%0A            'input', %7B%0A                'name': 'SubmissionUpload'%0A            %7D%0A        )%5B'value'%5D = entry%0A%0A        if message:%0A            submit_form.find(%0A                'textarea', 
+form_submission = browser.post(%0A            file_form_submit_url,%0A            data=%7B%0A                'fileName': entry,%0A                'contentLength': os.path.getsize(entry),%0A                'lastModifiedDateUtc': int(os.path.getmtime(entry) * 1000)%0A            %7D%0A        ).json()%0A%0A        file_submit_url = base + form_submission%5B'createUrl'%5D%0A%0A        with open(entry, 'rb') as submission_file:%0A            token = browser.post(%0A                file_submit_url,%0A                files=
 %7B%0A  
@@ -2079,17 +2079,16 @@
    '
-nam
+fil
 e': 
-'S
+s
 ubmi
@@ -2096,20 +2096,13 @@
 sion
-Description'
+_file
 %0A   
@@ -2134,79 +2134,334 @@
   ).
-insert(0, message)%0A%0A        browser.submit(submit_form, submit_page.url
+json()%5B'token'%5D%0A%0A        browser.post(%0A            entry_form_submit_url,%0A            data=json.dumps(%7B%0A                'blobFileTokens': %5Btoken%5D,%0A                'submissionDescription': message if message else ''%0A            %7D),%0A            headers=%7B%0A                'Content-Type': 'application/json'%0A            %7D%0A        
 )%0A%0A 

use new entry of submission