<?php

namespace Buckhill\LogMe\Model;

use Buckhill\LogMe\Facades\ElasticSearch;

class Message
{
    protected $model;

    public static function fromArray(array $record, $index, $type, $id = null)
    {
        $me = new static;

        $me->model = [
            'index' => $index,
            'type'  => $type,
            'id'    => $id ?? static::getID(),
            'body'  => $record
        ];

        return $me;
    }

    /**
     * Calculates the id based on microtime. This is used to guarantee insertion order so we can list records in insert
     * order without having to employ black magic
     *
     * @return string
     */
    public static function getID(): string
    {
        return (string)str_replace('.', '', microtime(true));
    }

    /**
     * Returns the array that we'll write to ES index
     *
     * @return array
     */
    public function getModel(): array
    {
        return $this->model;
    }

    /**
     * @return array
     */
    public function index(): array
    {
        return ElasticSearch::index($this->getModel());
    }
}