def handle_result(operation, process_id, printer, result, thread):
    #print(thread.process_id)
    #print(thread.params)
    process_region = printer.panel.find(process_id,0)
    status_region = printer.panel.find('Result:',process_region.begin())

    try:
        result = json.loads(result)
        if operation == 'compile' and 'actions' in result and util.to_bool(result['success']) == False:
            diff_merge_settings = config.settings.get('mm_diff_server_conflicts', False)
            if diff_merge_settings:
                if sublime.ok_cancel_dialog(result["body"], result["actions"][0].title()):
                    printer.panel.run_command('write_operation_status', {"text": " Diffing with server", 'region': [status_region.end(), status_region.end()+10] })
                    th = MavensMateDiffThread(thread.window, thread.view, result['tmp_file_path'])
                    th.start()
                    
                else:
                    printer.panel.run_command('write_operation_status', {"text": " "+result["actions"][1].title(), 'region': [status_region.end(), status_region.end()+10] })
            else:
                if sublime.ok_cancel_dialog(result["body"], "Overwrite Server Copy"):
                    printer.panel.run_command('write_operation_status', {"text": " Overwriting server copy", 'region': [status_region.end(), status_region.end()+10] })
                    thread.params['action'] = 'overwrite'
                    sublime.set_timeout(lambda: call('compile', params=thread.params), 100)   
                else:
                    printer.panel.run_command('write_operation_status', {"text": " "+result["actions"][1].title(), 'region': [status_region.end(), status_region.end()+10] })
   
        else:
            print_result_message(operation, process_id, status_region, result, printer, thread) 
            if operation == 'new_metadata' and 'success' in result and util.to_bool(result['success']) == True:
                if 'messages' in result:
                    if type(result['messages']) is not list:
                        result['messages'] = [result['messages']]
                    for m in result['messages']:
                        if 'package.xml' not in m['fileName']:
                            file_name = m['fileName']
                            location = util.mm_project_directory() + "/" + file_name.replace('unpackaged/', 'src/')
                            sublime.active_window().open_file(location)
                            break
            if 'success' in result and util.to_bool(result['success']) == True:
                if printer != None and len(ThreadTracker.get_pending_mm_panel_threads(thread.window)) == 0:
                    printer.hide()  
            elif 'State' in result and result['State'] == 'Completed' and len(ThreadTracker.get_pending_mm_panel_threads(thread.window)) == 0:
                #tooling api
                if printer != None:
                    printer.hide()
            if operation == 'refresh':            
                sublime.set_timeout(lambda: sublime.active_window().active_view().run_command('revert'), 200)
                util.clear_marked_line_numbers()
    except AttributeError:   
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: '+result+'\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: '+result
            printer.panel.run_command('write_operation_status', {'text': msg, 'region': [status_region.end(), status_region.end()+10] })
    except Exception:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: '+result+'\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: '+result
            printer.panel.run_command('write_operation_status', {'text': msg, 'region': [status_region.end(), status_region.end()+10] })
def handle_result(operation, process_id, printer, result, thread):
    #print(thread.process_id)
    #print(thread.params)
    process_region = printer.panel.find(process_id, 0)
    status_region = printer.panel.find('Result:', process_region.begin())

    try:
        result = json.loads(result)
        if operation == 'compile' and 'actions' in result and util.to_bool(
                result['success']) == False:
            diff_merge_settings = config.settings.get(
                'mm_diff_server_conflicts', False)
            if diff_merge_settings:
                if sublime.ok_cancel_dialog(result["body"],
                                            result["actions"][0].title()):
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " Diffing with server",
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
                    th = MavensMateDiffThread(thread.window, thread.view,
                                              result['tmp_file_path'])
                    th.start()

                else:
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " " + result["actions"][1].title(),
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
            else:
                if sublime.ok_cancel_dialog(result["body"],
                                            "Overwrite Server Copy"):
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " Overwriting server copy",
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
                    thread.params['action'] = 'overwrite'
                    sublime.set_timeout(
                        lambda: call('compile', params=thread.params), 100)
                else:
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " " + result["actions"][1].title(),
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })

        elif operation == 'test_async':
            responses = []
            if len(result) == 1:
                res = result[0]
                response_string = ""
                if 'detailed_results' in res:
                    all_tests_passed = True
                    for r in res['detailed_results']:
                        if r["Outcome"] != "Pass":
                            all_tests_passed = False
                            break

                    if all_tests_passed:
                        response_string += '[TEST RESULT]: PASS'
                    else:
                        response_string += '[TEST RESULT]: FAIL'

                    for r in res['detailed_results']:
                        if r["Outcome"] == "Pass":
                            pass  #dont need to write anything here...
                        else:
                            response_string += '\n'
                            rstring = "====METHOD RESULT===="
                            rstring += "\n"
                            rstring += "{0} : {1}".format(
                                r["MethodName"], r["Outcome"])

                            rstring += "\n\n"
                            rstring += "====STACK TRACE===="
                            rstring += "\n"
                            rstring += r["StackTrace"]

                            rstring += "\n\n"
                            rstring += "====MESSAGE===="
                            rstring += "\n"
                            rstring += r["Message"]
                            rstring += "\n"
                            #responses.append("{0} | {1} | {2} | {3}\n".format(r["MethodName"], r["Outcome"], r["StackTrace"], r["Message"]))
                            responses.append(rstring)
                    response_string += "\n"
                    response_string += "\n\n".join(responses)
                    printer.panel.run_command(
                        'write_operation_status', {
                            'text':
                            response_string,
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
                    printer.scroll_to_bottom()
                else:
                    printer.panel.run_command(
                        'write_operation_status', {
                            'text':
                            json.dumps(result),
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
            else:
                pass  #TODO

        elif operation == 'run_apex_script':
            if result["success"] == True and result["compiled"] == True:
                printer.panel.run_command(
                    'write_operation_status', {
                        'text': " Success",
                        'region':
                        [status_region.end(),
                         status_region.end() + 10]
                    })
                thread.window.open_file(result["log_location"],
                                        sublime.TRANSIENT)
            elif result["success"] == False:
                message = " [OPERATION FAILED]: "
                if "compileProblem" in result and result[
                        "compileProblem"] != None:
                    message += "[Line: " + str(
                        result["line"]) + ", Column: " + str(
                            result["column"]
                        ) + "] " + result["compileProblem"] + "\n"
                if "exceptionMessage" in result and result[
                        "exceptionMessage"] != None:
                    message += result["exceptionMessage"] + "\n"
                if "exceptionStackTrace" in result and result[
                        "exceptionStackTrace"] != None:
                    message += result["exceptionStackTrace"] + "\n"
                printer.panel.run_command(
                    'write_operation_status', {
                        'text': message,
                        'region':
                        [status_region.end(),
                         status_region.end() + 10]
                    })
        else:
            print_result_message(operation, process_id, status_region, result,
                                 printer, thread)
            if operation == 'new_metadata' and 'success' in result and util.to_bool(
                    result['success']) == True:
                if 'messages' in result:
                    if type(result['messages']) is not list:
                        result['messages'] = [result['messages']]
                    for m in result['messages']:
                        if 'package.xml' not in m['fileName']:
                            file_name = m['fileName']
                            location = os.path.join(
                                util.mm_project_directory(),
                                file_name.replace('unpackaged/', 'src/'))
                            sublime.active_window().open_file(location)
                            break
            if 'success' in result and util.to_bool(result['success']) == True:
                if printer != None and len(
                        ThreadTracker.get_pending_mm_panel_threads(
                            thread.window)) == 0:
                    printer.hide()
            elif 'State' in result and result['State'] == 'Completed' and len(
                    ThreadTracker.get_pending_mm_panel_threads(
                        thread.window)) == 0:
                #tooling api
                if printer != None:
                    printer.hide()
            if operation == 'refresh':
                sublime.set_timeout(
                    lambda: sublime.active_window().active_view().run_command(
                        'revert'), 200)
                util.clear_marked_line_numbers()
    except AttributeError as e:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: ' + result + '\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: ' + result
            print(e)
            print(sys.exc_info()[0])
            printer.panel.run_command(
                'write_operation_status', {
                    'text': msg,
                    'region': [status_region.end(),
                               status_region.end() + 10]
                })
    except Exception as e:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: ' + result + '\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: ' + result
            print(e)
            print(sys.exc_info()[0])
            printer.panel.run_command(
                'write_operation_status', {
                    'text': msg,
                    'region': [status_region.end(),
                               status_region.end() + 10]
                })
def handle_result(operation, process_id, printer, result, thread):
    #print(thread.process_id)
    #print(thread.params)
    process_region = printer.panel.find(process_id,0)
    status_region = printer.panel.find('Result:',process_region.begin())

    try:
        result = json.loads(result)
        if operation == 'compile' and 'actions' in result and util.to_bool(result['success']) == False:
            diff_merge_settings = config.settings.get('mm_diff_server_conflicts', False)
            if diff_merge_settings:
                if sublime.ok_cancel_dialog(result["body"], result["actions"][0].title()):
                    printer.panel.run_command('write_operation_status', {"text": " Diffing with server", 'region': [status_region.end(), status_region.end()+10] })
                    th = MavensMateDiffThread(thread.window, thread.view, result['tmp_file_path'])
                    th.start()
                    
                else:
                    printer.panel.run_command('write_operation_status', {"text": " "+result["actions"][1].title(), 'region': [status_region.end(), status_region.end()+10] })
            else:
                if sublime.ok_cancel_dialog(result["body"], "Overwrite Server Copy"):
                    printer.panel.run_command('write_operation_status', {"text": " Overwriting server copy", 'region': [status_region.end(), status_region.end()+10] })
                    thread.params['action'] = 'overwrite'
                    sublime.set_timeout(lambda: call('compile', params=thread.params), 100)   
                else:
                    printer.panel.run_command('write_operation_status', {"text": " "+result["actions"][1].title(), 'region': [status_region.end(), status_region.end()+10] })
   
        elif operation == 'test_async':
            responses = []
            if len(result) == 1:
                res = result[0]
                response_string = ""
                if 'detailed_results' in res:
                    all_tests_passed = True
                    for r in res['detailed_results']:
                        if r["Outcome"] != "Pass":
                            all_tests_passed = False
                            break

                    if all_tests_passed:
                        response_string += '[TEST RESULT]: PASS'
                    else:
                        response_string += '[TEST RESULT]: FAIL'
                    
                    for r in res['detailed_results']:
                        if r["Outcome"] == "Pass":
                            pass #dont need to write anything here...
                        else:
                            response_string += '\n'
                            rstring = "====METHOD RESULT===="
                            rstring += "\n"
                            rstring += "{0} : {1}".format(r["MethodName"], r["Outcome"])
                            
                            rstring += "\n\n"
                            rstring += "====STACK TRACE===="
                            rstring += "\n"
                            rstring += r["StackTrace"]

                            rstring += "\n\n"
                            rstring += "====MESSAGE===="
                            rstring += "\n"
                            rstring += r["Message"]
                            rstring += "\n"
                            #responses.append("{0} | {1} | {2} | {3}\n".format(r["MethodName"], r["Outcome"], r["StackTrace"], r["Message"]))
                            responses.append(rstring)
                    response_string += "\n"       
                    response_string += "\n\n".join(responses)
                    printer.panel.run_command('write_operation_status', {'text': response_string, 'region': [status_region.end(), status_region.end()+10] })
                    printer.scroll_to_bottom()
                else:
                    printer.panel.run_command('write_operation_status', {'text': json.dumps(result), 'region': [status_region.end(), status_region.end()+10] })
            else:
                pass #TODO
        
        elif operation == 'run_apex_script':
            if result["success"] == True and result["compiled"] == True:
                printer.panel.run_command('write_operation_status', {'text': " Success", 'region': [status_region.end(), status_region.end()+10] })
                thread.window.open_file(result["log_location"], sublime.TRANSIENT)
            elif result["success"] == False:
                message = " [OPERATION FAILED]: "
                if "compileProblem" in result and result["compileProblem"] != None:
                    message += "[Line: "+str(result["line"]) + ", Column: "+str(result["column"])+"] " + result["compileProblem"] + "\n"
                if "exceptionMessage" in result and result["exceptionMessage"] != None:
                    message += result["exceptionMessage"] + "\n"
                if "exceptionStackTrace" in result and result["exceptionStackTrace"] != None:
                    message += result["exceptionStackTrace"] + "\n"
                printer.panel.run_command('write_operation_status', {'text': message, 'region': [status_region.end(), status_region.end()+10] })
        else:
            print_result_message(operation, process_id, status_region, result, printer, thread) 
            if operation == 'new_metadata' and 'success' in result and util.to_bool(result['success']) == True:
                if 'messages' in result:
                    if type(result['messages']) is not list:
                        result['messages'] = [result['messages']]
                    for m in result['messages']:
                        if 'package.xml' not in m['fileName']:
                            file_name = m['fileName']
                            location = os.path.join(util.mm_project_directory(),file_name.replace('unpackaged/', 'src/'))
                            sublime.active_window().open_file(location)
                            break
            if 'success' in result and util.to_bool(result['success']) == True:
                if printer != None and len(ThreadTracker.get_pending_mm_panel_threads(thread.window)) == 0:
                    printer.hide()  
            elif 'State' in result and result['State'] == 'Completed' and len(ThreadTracker.get_pending_mm_panel_threads(thread.window)) == 0:
                #tooling api
                if printer != None:
                    printer.hide()
            if operation == 'refresh':            
                sublime.set_timeout(lambda: sublime.active_window().active_view().run_command('revert'), 200)
                util.clear_marked_line_numbers()
    except AttributeError as e:   
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: '+result+'\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: '+result
            print(e)
            print(sys.exc_info()[0])
            printer.panel.run_command('write_operation_status', {'text': msg, 'region': [status_region.end(), status_region.end()+10] })
    except Exception as e:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: '+result+'\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: '+result
            print(e)
            print(sys.exc_info()[0])
            printer.panel.run_command('write_operation_status', {'text': msg, 'region': [status_region.end(), status_region.end()+10] })
def handle_result(operation, process_id, printer, result, thread):
    #print(thread.process_id)
    #print(thread.params)
    process_region = printer.panel.find(process_id, 0)
    status_region = printer.panel.find('Result:', process_region.begin())

    try:
        result = json.loads(result)
        if operation == 'compile' and 'actions' in result and util.to_bool(
                result['success']) == False:
            diff_merge_settings = config.settings.get(
                'mm_diff_server_conflicts', False)
            if diff_merge_settings:
                if sublime.ok_cancel_dialog(result["body"],
                                            result["actions"][0].title()):
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " Diffing with server",
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
                    th = MavensMateDiffThread(thread.window, thread.view,
                                              result['tmp_file_path'])
                    th.start()

                else:
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " " + result["actions"][1].title(),
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
            else:
                if sublime.ok_cancel_dialog(result["body"],
                                            "Overwrite Server Copy"):
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " Overwriting server copy",
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })
                    thread.params['action'] = 'overwrite'
                    sublime.set_timeout(
                        lambda: call('compile', params=thread.params), 100)
                else:
                    printer.panel.run_command(
                        'write_operation_status', {
                            "text":
                            " " + result["actions"][1].title(),
                            'region':
                            [status_region.end(),
                             status_region.end() + 10]
                        })

        else:
            print_result_message(operation, process_id, status_region, result,
                                 printer, thread)
            if operation == 'new_metadata' and 'success' in result and util.to_bool(
                    result['success']) == True:
                if 'messages' in result:
                    if type(result['messages']) is not list:
                        result['messages'] = [result['messages']]
                    for m in result['messages']:
                        if 'package.xml' not in m['fileName']:
                            file_name = m['fileName']
                            location = util.mm_project_directory(
                            ) + "/" + file_name.replace('unpackaged/', 'src/')
                            sublime.active_window().open_file(location)
                            break
            if 'success' in result and util.to_bool(result['success']) == True:
                if printer != None and len(
                        ThreadTracker.get_pending_mm_panel_threads(
                            thread.window)) == 0:
                    printer.hide()
            elif 'State' in result and result['State'] == 'Completed' and len(
                    ThreadTracker.get_pending_mm_panel_threads(
                        thread.window)) == 0:
                #tooling api
                if printer != None:
                    printer.hide()
            if operation == 'refresh':
                sublime.set_timeout(
                    lambda: sublime.active_window().active_view().run_command(
                        'revert'), 200)
                util.clear_marked_line_numbers()
    except AttributeError:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: ' + result + '\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: ' + result
            printer.panel.run_command(
                'write_operation_status', {
                    'text': msg,
                    'region': [status_region.end(),
                               status_region.end() + 10]
                })
    except Exception:
        if printer != None:
            printer.write('\n[RESPONSE FROM MAVENSMATE]: ' + result + '\n')
            msg = ' [OPERATION FAILED]: Whoops, unable to parse the response. Please report this issue at https://github.com/joeferraro/MavensMate-SublimeText\n'
            msg += '[RESPONSE FROM MAVENSMATE]: ' + result
            printer.panel.run_command(
                'write_operation_status', {
                    'text': msg,
                    'region': [status_region.end(),
                               status_region.end() + 10]
                })