package rbasamoyai.createbigcannons.cannonmount;

import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TranslatableComponent;
import com.simibubi.create.foundation.utility.AngleHelper;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.entity.player.Player;
import net.minecraft.core.Vec3i;
import com.simibubi.create.AllSoundEvents;
import net.minecraft.world.entity.Entity;
import com.simibubi.create.content.contraptions.components.structureMovement.Contraption;
import com.simibubi.create.foundation.utility.ServerSpeedProvider;
import java.util.function.Supplier;
import com.simibubi.create.content.contraptions.components.structureMovement.AbstractContraptionEntity;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.util.Mth;
import net.minecraft.world.level.block.state.properties.Property;
import net.minecraft.core.Direction;
import rbasamoyai.createbigcannons.CBCBlocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.core.BlockPos;
import net.minecraft.world.level.block.entity.BlockEntityType;
import com.simibubi.create.content.contraptions.components.structureMovement.AssemblyException;
import net.minecraft.world.level.block.state.properties.DirectionProperty;
import com.simibubi.create.content.contraptions.components.structureMovement.IDisplayAssemblyExceptions;
import com.simibubi.create.content.contraptions.base.KineticTileEntity;

public class CannonMountBlockEntity extends KineticTileEntity implements IDisplayAssemblyExceptions
{
    private static final DirectionProperty HORIZONTAL_FACING;
    private AssemblyException lastException;
    private PitchOrientedContraptionEntity mountedContraption;
    private boolean running;
    private float cannonYaw;
    private float cannonPitch;
    private float prevYaw;
    private float prevPitch;
    private float clientYawDiff;
    private float clientPitchDiff;
    float yawSpeed;
    
    public CannonMountBlockEntity(final BlockEntityType<? extends CannonMountBlockEntity> typeIn, final BlockPos pos, final BlockState state) {
        super((BlockEntityType)typeIn, pos, state);
        this.lastException = null;
        if (CBCBlocks.CANNON_MOUNT.has(state)) {
            this.cannonYaw = ((Direction)state.m_61143_((Property)CannonMountBlockEntity.HORIZONTAL_FACING)).m_122435_();
        }
        this.setLazyTickRate(3);
    }
    
    public void tick() {
        super.tick();
        if (this.mountedContraption != null && !this.mountedContraption.m_6084_()) {
            this.mountedContraption = null;
        }
        this.prevYaw = this.cannonYaw;
        this.prevPitch = this.cannonPitch;
        if (this.f_58857_.f_46443_) {
            this.clientYawDiff *= 0.5f;
            this.clientPitchDiff *= 0.5f;
        }
        if (!this.running) {
            if (CBCBlocks.CANNON_MOUNT.has(this.m_58900_())) {
                this.cannonYaw = ((Direction)this.m_58900_().m_61143_((Property)CannonMountBlockEntity.HORIZONTAL_FACING)).m_122435_();
            }
            return;
        }
        if (this.mountedContraption == null || !this.mountedContraption.isStalled()) {
            final float yawSpeed = this.getAngularSpeed(this::getYawSpeed, this.clientYawDiff);
            final float pitchSpeed = this.getAngularSpeed(this::getSpeed, this.clientPitchDiff);
            final float newYaw = this.cannonYaw + yawSpeed;
            final float newPitch = this.cannonPitch + pitchSpeed;
            this.cannonYaw = newYaw % 360.0f;
            if (this.mountedContraption == null) {
                this.cannonPitch = 0.0f;
            }
            else {
                final Direction dir = this.getContraptionDirection();
                final boolean flag = dir.m_122421_() == Direction.AxisDirection.POSITIVE == (dir.m_122434_() == Direction.Axis.X);
                final float cu = flag ? 60.0f : 30.0f;
                final float cd = flag ? -30.0f : -60.0f;
                this.cannonPitch = Mth.m_14036_(newPitch % 360.0f, cd, cu);
            }
        }
        this.applyRotation();
    }
    
    public boolean isRunning() {
        return this.running;
    }
    
    protected void applyRotation() {
        if (this.mountedContraption == null) {
            return;
        }
        this.mountedContraption.prevPitch = this.prevPitch;
        this.mountedContraption.pitch = this.cannonPitch;
        this.mountedContraption.prevYaw = this.prevYaw;
        this.mountedContraption.yaw = this.cannonYaw;
    }
    
    public void onRedstoneUpdate(final boolean assemblyPowered, final boolean prevAssemblyPowered, final boolean firePowered, final boolean prevFirePowered) {
        if (assemblyPowered != prevAssemblyPowered) {
            this.f_58857_.m_7731_(this.f_58858_, (BlockState)this.m_58900_().m_61124_((Property)CannonMountBlock.ASSEMBLY_POWERED, (Comparable)assemblyPowered), 3);
            if (assemblyPowered) {
                try {
                    this.assemble();
                    this.lastException = null;
                }
                catch (AssemblyException e) {
                    this.lastException = e;
                    this.sendData();
                }
            }
            else {
                this.disassemble();
                this.sendData();
            }
        }
        if (firePowered != prevFirePowered) {
            this.f_58857_.m_7731_(this.f_58858_, (BlockState)this.m_58900_().m_61124_((Property)CannonMountBlock.FIRE_POWERED, (Comparable)firePowered), 3);
            if (firePowered && this.running && this.mountedContraption != null && this.f_58857_ instanceof ServerLevel) {
                ((MountedCannonContraption)this.mountedContraption.getContraption()).fireShot((ServerLevel)this.f_58857_, (AbstractContraptionEntity)this.mountedContraption);
            }
        }
    }
    
    public void lazyTick() {
        super.lazyTick();
        if (this.running && this.mountedContraption != null) {
            this.sendData();
        }
    }
    
    public float getPitchOffset(final float partialTicks) {
        if (!this.running) {
            return this.cannonPitch;
        }
        return this.cannonPitch + convertToAngular(this.getSpeed()) * 0.125f * partialTicks;
    }
    
    public void setPitch(final float pitch) {
        this.cannonPitch = pitch;
    }
    
    public float getYawSpeed() {
        return this.overStressed ? 0.0f : this.getTheoreticalYawSpeed();
    }
    
    public float getTheoreticalYawSpeed() {
        return this.yawSpeed;
    }
    
    public float getYawOffset(final float partialTicks) {
        if (!this.running) {
            return this.cannonYaw;
        }
        return this.cannonYaw + convertToAngular(this.getYawSpeed()) * 0.125f * partialTicks;
    }
    
    public void setYaw(final float yaw) {
        this.cannonYaw = yaw;
    }
    
    public Direction getContraptionDirection() {
        return (this.mountedContraption == null) ? Direction.NORTH : ((MountedCannonContraption)this.mountedContraption.getContraption()).initialOrientation();
    }
    
    public float getAngularSpeed(final Supplier<Float> sup, final float clientDiff) {
        float speed = convertToAngular((float)sup.get()) * 0.125f;
        if (sup.get() == 0.0f) {
            speed = 0.0f;
        }
        if (this.f_58857_.f_46443_) {
            speed *= ServerSpeedProvider.get();
            speed += clientDiff / 3.0f;
        }
        return speed;
    }
    
    protected void assemble() throws AssemblyException {
        if (!CBCBlocks.CANNON_MOUNT.has(this.m_58900_())) {
            return;
        }
        final BlockPos assemblyPos = this.f_58858_.m_6630_(2);
        if (this.f_58857_.m_151570_(assemblyPos)) {
            throw cannonBlockOutsideOfWorld(assemblyPos);
        }
        final MountedCannonContraption mountedCannon = new MountedCannonContraption();
        if (!mountedCannon.assemble(this.f_58857_, assemblyPos)) {
            return;
        }
        this.running = true;
        mountedCannon.removeBlocksFromWorld(this.f_58857_, BlockPos.f_121853_);
        final PitchOrientedContraptionEntity contraptionEntity = PitchOrientedContraptionEntity.create(this.f_58857_, (Contraption)mountedCannon, (Direction)this.m_58900_().m_61143_((Property)CannonMountBlockEntity.HORIZONTAL_FACING));
        this.mountedContraption = contraptionEntity;
        this.resetContraptionToOffset();
        this.f_58857_.m_7967_((Entity)contraptionEntity);
        this.sendData();
        AllSoundEvents.CONTRAPTION_ASSEMBLE.playOnServer(this.f_58857_, (Vec3i)this.f_58858_);
    }
    
    public void disassemble() {
        if (!this.running && this.mountedContraption == null) {
            return;
        }
        if (this.mountedContraption != null) {
            this.resetContraptionToOffset();
            this.mountedContraption.disassemble();
            AllSoundEvents.CONTRAPTION_DISASSEMBLE.playOnServer(this.f_58857_, (Vec3i)this.f_58858_);
        }
        this.running = false;
        if (this.f_58859_) {
            ((CannonMountBlock)CBCBlocks.CANNON_MOUNT.get()).m_5707_(this.f_58857_, this.f_58858_, this.m_58900_(), (Player)null);
        }
    }
    
    protected void resetContraptionToOffset() {
        if (this.mountedContraption == null) {
            return;
        }
        this.cannonPitch = 0.0f;
        this.cannonYaw = ((Direction)this.m_58900_().m_61143_((Property)CannonMountBlockEntity.HORIZONTAL_FACING)).m_122435_();
        this.applyRotation();
        final Vec3 vec = Vec3.m_82539_((Vec3i)this.f_58858_.m_6630_(2));
        this.mountedContraption.m_146884_(vec);
    }
    
    public float calculateStressApplied() {
        if (this.running && this.mountedContraption != null) {
            final MountedCannonContraption contraption = (MountedCannonContraption)this.mountedContraption.getContraption();
            return contraption.getWeightForStress();
        }
        return 0.0f;
    }
    
    protected void write(final CompoundTag tag, final boolean clientPacket) {
        super.write(tag, clientPacket);
        tag.m_128379_("Running", this.running);
        tag.m_128350_("CannonYaw", this.cannonYaw);
        tag.m_128350_("CannonPitch", this.cannonPitch);
        tag.m_128350_("YawSpeed", this.yawSpeed);
        AssemblyException.write(tag, this.lastException);
    }
    
    protected void read(final CompoundTag tag, final boolean clientPacket) {
        super.read(tag, clientPacket);
        this.running = tag.m_128471_("Running");
        this.cannonYaw = tag.m_128457_("CannonYaw");
        this.cannonPitch = tag.m_128457_("CannonPitch");
        this.lastException = AssemblyException.read(tag);
        this.yawSpeed = tag.m_128457_("YawSpeed");
        if (!clientPacket) {
            return;
        }
        if (this.running) {
            if (this.mountedContraption == null || !this.mountedContraption.isStalled()) {
                this.clientYawDiff = AngleHelper.getShortestAngleDiff((double)this.prevYaw, (double)this.cannonYaw);
                this.clientPitchDiff = AngleHelper.getShortestAngleDiff((double)this.prevPitch, (double)this.cannonPitch);
                this.prevYaw = this.cannonYaw;
                this.prevPitch = this.cannonPitch;
            }
        }
        else {
            this.mountedContraption = null;
        }
    }
    
    protected void setRemovedNotDueToChunkUnload() {
        this.f_58859_ = true;
        if (!this.f_58857_.f_46443_) {
            this.disassemble();
        }
        super.setRemovedNotDueToChunkUnload();
    }
    
    public void attach(final PitchOrientedContraptionEntity contraption) {
        this.mountedContraption = contraption;
        if (!this.f_58857_.f_46443_) {
            this.running = true;
            this.sendData();
        }
    }
    
    public boolean isAttachedTo(final PitchOrientedContraptionEntity contraption) {
        return this.mountedContraption == contraption;
    }
    
    public AssemblyException getLastAssemblyException() {
        return this.lastException;
    }
    
    public static AssemblyException cannonBlockOutsideOfWorld(final BlockPos pos) {
        return new AssemblyException((Component)new TranslatableComponent("exception.createbigcannons.cannon_mount.cannonBlockOutsideOfWorld", new Object[] { pos.m_123341_(), pos.m_123342_(), pos.m_123343_() }));
    }
    
    static {
        HORIZONTAL_FACING = BlockStateProperties.f_61374_;
    }
} 

Javascript Online Compiler

Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

About Javascript

Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

Key Features

  • Open-source
  • Just-in-time compiled language
  • Embedded along with HTML and makes web pages alive
  • Originally named as LiveScript.
  • Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc.

Syntax help

STDIN Example

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log("Hello, " + line);
});

variable declaration

KeywordDescriptionScope
varVar is used to declare variables(old way of declaring variables)Function or global scope
letlet is also used to declare variables(new way)Global or block Scope
constconst is used to declare const values. Once the value is assigned, it can not be modifiedGlobal or block Scope

Backtick Strings

Interpolation

let greetings = `Hello ${name}`

Multi line Strings

const msg = `
hello
world!
`

Arrays

An array is a collection of items or values.

Syntax:

let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);

Example:

let mobiles = ["iPhone", "Samsung", "Pixel"];

// accessing an array
console.log(mobiles[0]);

// changing an array element
mobiles[3] = "Nokia";

Arrow functions

Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

Syntax:

() => expression

Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
                                    .map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);

De-structuring

Arrays

let [firstName, lastName] = ['Foo', 'Bar']

Objects

let {firstName, lastName} = {
  firstName: 'Foo',
  lastName: 'Bar'
}

rest(...) operator

 const {
    title,
    firstName,
    lastName,
    ...rest
  } = record;

Spread(...) operator

//Object spread
const post = {
  ...options,
  type: "new"
}
//array spread
const users = [
  ...adminUsers,
  ...normalUsers
]

Functions

function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
  console.log(`Hello ${name}!`);
}
 
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar

Loops

1. If:

IF is used to execute a block of code based on a condition.

Syntax

if(condition){
    // code
}

2. If-Else:

Else part is used to execute the block of code when the condition fails.

Syntax

if(condition){
    // code
} else {
    // code
}

3. Switch:

Switch is used to replace nested If-Else statements.

Syntax

switch(condition){
    case 'value1' :
        //code
        [break;]
    case 'value2' :
        //code
        [break;]
    .......
    default :
        //code
        [break;]
}

4. For

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
//code  
} 

5. While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
  // code 
}  

6. Do-While

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
  // code 
} while (condition); 

Classes

ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

Syntax:

class className {
  constructor() { ... } //Mandatory Class method
  method1() { ... }
  method2() { ... }
  ...
}

Example:

class Mobile {
  constructor(model) {
    this.name = model;
  }
}

mbl = new Mobile("iPhone");