/**
 * An ES6 screeps game engine.
 *
 * An attempt to conquer screeps, the first MMO strategy sandbox
 * game for programmers!
 *
 * @author    Geert Hauwaerts <geert@hauwaerts.be>
 * @copyright Copyright (c) Geert Hauwaerts
 * @license   MIT License
 */

import Creep from './Creep';

/**
 * Process builder creeps.
 *
 * @extends Creep
 */
export default class CreepBuilder extends Creep {
  /**
   * Load the builder creep.
   *
   * @returns {void}
   */
  load() {
    this.deploy();
  }

  /**
   * Deploy the build creep.
   *
   * @returns {void}
   */
  deploy() {
    const task = this.getTask();

    if (!task) {
      return;
    }

    this.startConstruction(task);
  }

  /**
   * Assign a construction task to a creep.
   *
   * @param   {object} task The task to perform.
   * @returns {void}
   */
  startConstruction(task) {
    const status = {};
    const target = this.game.getObjectById(task.target);

    if (!target) {
      this.completeTask();
      return;
    }

    if (this.creep.carry.energy === 0) {
      return;
    }

    switch (task.action) {
      case 'repair':
        if (target.hits === target.hitsMax) {
          this.completeTask();
          return;
        }

        status.action = this.creep.repair(target);
        break;
      case 'build':
        status.action = this.creep.build(target);
        break;
      case 'controller':
        status.action = this.creep.upgradeController(target);
        break;
      default:
        this.log('warn', `Unsupported construction action: ${task.action}`);
        break;
    }

    if (status.action === ERR_NOT_IN_RANGE) {
      status.move = this.creep.moveTo(target);

      if (status.move === ERR_NO_PATH) {
        this.log('info', status.move);
      } else if ((status.move !== OK) && (status.move !== ERR_TIRED)) {
        this.log('error', status.move);
        this.forgetTask();
      }
    } else if (status.action === ERR_NO_BODYPART) {
      this.retire();
    } else {
      this.log('error', status.action);
    }
  }
}
